package org.visionlibrary.image.event;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.visionlibrary.image.event.events.IProcFinishEvent;
import org.visionlibrary.image.event.events.IProcStartEvent;
import org.visionlibrary.image.event.events.IProcTickEvent;
import org.visionlibrary.image.event.listeners.IProcFinishEventListener;
import org.visionlibrary.image.event.listeners.IProcStartEventListener;
import org.visionlibrary.image.event.listeners.IProcTickEventListener;


public class IProcEventGenerator {
	private List<IProcTickEventListener> _tlisteners = new ArrayList<IProcTickEventListener>();
	private List<IProcStartEventListener> _slisteners = new ArrayList<IProcStartEventListener>();
	private List<IProcFinishEventListener> _flisteners = new ArrayList<IProcFinishEventListener>();

	protected synchronized void tick() {
		_fireTickEvent();
	}
	
	protected synchronized void start() {
		_fireStartEvent();
	}
	
	protected synchronized void finish() {
		_fireFinishEvent();
	}
	
	public synchronized void addFinishEventListener(IProcFinishEventListener l) {
		_flisteners.add(l);
	}
	
	public synchronized void removeFinishEventListener(IProcFinishEventListener l) {
		_flisteners.remove(l);
	}
	
	public synchronized void addStartEventListener(IProcStartEventListener l) {
		_slisteners.add(l);
	}
	
	public synchronized void removeStartEventListener(IProcStartEventListener l) {
		_slisteners.remove(l);
	}
	
	public synchronized void addTickEventListener(IProcTickEventListener l) {
		_tlisteners.add(l);
	}

	public synchronized void removeTickEventListener(IProcTickEventListener l) {
		_tlisteners.remove(l);
	}

	private synchronized void _fireStartEvent() {
		IProcStartEvent start = new IProcStartEvent(this);
		
		Iterator<IProcStartEventListener> listeners = _slisteners.iterator();
		while (listeners.hasNext())
			listeners.next().iProcStarted(start);
	}
	
	private synchronized void _fireTickEvent() {
		IProcTickEvent tick = new IProcTickEvent(this);
		
		Iterator<IProcTickEventListener> listeners = _tlisteners.iterator();
		while (listeners.hasNext())
			listeners.next().tickReceived(tick);
	}
	
	private synchronized void _fireFinishEvent() {
		IProcFinishEvent finish = new IProcFinishEvent(this);
		
		Iterator<IProcFinishEventListener> listeners = _flisteners.iterator();
		while (listeners.hasNext())
			listeners.next().iProcFinished(finish);
	}
}
